package com.example.app.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import androidx.appcompat.widget.AppCompatTextView
import com.example.app.R
import com.example.core.utils.dp2px
import java.util.*

//class CodeView   : AppCompatTextView {
//class CodeView constructor(context: Context, attrs: AttributeSet?) : AppCompatTextView (context, attrs)  {
//@JvmOverloads在java调用时才会显示多个重载方法，这时constructor关键字不可省略
class CodeView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : AppCompatTextView(context, attrs) {
    //主构造中添加默认值这样它就是一个可选参数与下面1个参数构造重载了，将原本声明的2个构造简化成一个构造
    private val paint: Paint = Paint().apply {
        isAntiAlias = true;
        style = Paint.Style.STROKE;
        color = getContext().getColor(R.color.colorAccent);
//      t.setStrokeWidth(Utils.dp2px(6f));
//      t.strokeWidth = dp2px(6f);
        strokeWidth = 6f.dp2px();//扩展函数
    }

    private val codeList = arrayOf(
            "kotlin",
            "android",
            "java",
            "http",
            "https",
            "okhttp",
            "retrofit",
            "tcp/ip"
    )
    /*   constructor(context: Context) : this(context, null) {
       }*/

    /* constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
         setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f)
         gravity = Gravity.CENTER
         setBackgroundColor(getContext().getColor(R.color.colorPrimary));
         setTextColor(Color.WHITE);

         paint.isAntiAlias = true;
         paint.style = Paint.Style.STROKE;
         paint.color = getContext().getColor(R.color.colorAccent);
 //        paint.setStrokeWidth(Utils.dp2px(6f));
 //        paint.strokeWidth = dp2px(6f);
         paint.strokeWidth = 6f.dp2px();

         updateCode();
     }*/
    init {
        setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f)
        gravity = Gravity.CENTER
        setBackgroundColor(getContext().getColor(R.color.colorPrimary));
        setTextColor(Color.WHITE);

//        paint.isAntiAlias = true;
//        paint.style = Paint.Style.STROKE;
//        paint.color = getContext().getColor(R.color.colorAccent);
////        paint.setStrokeWidth(Utils.dp2px(6f));
////        paint.strokeWidth = dp2px(6f);
//        paint.strokeWidth = 6f.dp2px();//扩展函数

        updateCode();
    }

    public fun updateCode() {
        val random = Random().nextInt(codeList.size);
        val code = codeList[random];
        text = code;
    }

    override fun onDraw(canvas: Canvas?) {
        canvas?.drawLine(0f, height.toFloat(), width.toFloat(), 0f, paint);
        super.onDraw(canvas)
    }
//    @Override
//    protected void onDraw(Canvas canvas) {
//        canvas.drawLine(0f, getHeight(), getWidth(), 0f, paint);
//        super.onDraw(canvas);
//    }
}

